package com.example.nocodesqlapi.service;

import com.alibaba.fastjson.JSON;
import com.example.nocodesqlapi.model.SqlConfig;
import com.example.nocodesqlapi.model.SqlVariable;
import com.example.nocodesqlapi.repository.SqlConfigRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class SqlConfigService {
    
    @Autowired
    private SqlConfigRepository sqlConfigRepository;
    
    /**
     * 获取所有SQL配置
     */
    public List<SqlConfig> getAllSqlConfigs() {
        return sqlConfigRepository.findAll();
    }
    
    /**
     * 根据ID获取SQL配置
     */
    public Optional<SqlConfig> getSqlConfigById(Long id) {
        return sqlConfigRepository.findById(id);
    }
    
    /**
     * 根据API路径获取启用的SQL配置
     */
    public Optional<SqlConfig> getEnabledSqlConfigByApiPath(String apiPath) {
        return sqlConfigRepository.findByApiPathAndEnabledTrue(apiPath);
    }
    
    /**
     * 保存SQL配置
     */
    @Transactional
    public SqlConfig saveSqlConfig(SqlConfig sqlConfig) {
        // 验证API路径格式
        if (!sqlConfig.getApiPath().startsWith("/")) {
            sqlConfig.setApiPath("/" + sqlConfig.getApiPath());
        }
        
        // 检查API路径是否已存在
        if (sqlConfig.getId() == null && sqlConfigRepository.existsByApiPath(sqlConfig.getApiPath())) {
            throw new RuntimeException("API路径已存在: " + sqlConfig.getApiPath());
        }
        
        return sqlConfigRepository.save(sqlConfig);
    }
    
    /**
     * 删除SQL配置
     */
    @Transactional
    public void deleteSqlConfig(Long id) {
        sqlConfigRepository.deleteById(id);
    }
    
    /**
     * 解析变量配置
     */
    public List<SqlVariable> parseVariables(SqlConfig sqlConfig) {
        if (sqlConfig.getVariables() == null || sqlConfig.getVariables().trim().isEmpty()) {
            return List.of();
        }
        return JSON.parseArray(sqlConfig.getVariables(), SqlVariable.class);
    }
}
